package cn.itsource.basic.job.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.itsource.order.domain.OrderAdopt;
import cn.itsource.order.service.IOrderAdoptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* 定时任务执行类
* @author wangcp
* @date 2021/05/10 10:42
**/
@Service //交给spring管理，就可以注入
public class TaskServiceImpl implements TaskService {

    @Autowired
    private IOrderAdoptService orderAdoptService;

    @Async("taskExecutor") //异步
    @Override
    public void executeRemindMessage() throws InterruptedException {
/*        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前运行线的程名称：" + Thread.currentThread().getName() + " ,执行定时任务了,执行时间为：" + sdf.format(date));
        Thread.sleep(1500);*/

        //需求：当订单到了30分钟还没有支付，取消
        //判断条件：1.状态必须是未支付state=0  2.满足超过30分钟

        //1.查询30分钟之前未支付的订单 （获取当前时间往前推30分钟的时间）
        //2022-11-27 11:45:40
        String time = beforeMiddleHourTime();
        List<OrderAdopt> orderAdopts = orderAdoptService.findCancelOrder(time);

        if (CollectionUtil.isEmpty(orderAdopts)){
            return;
        }

        for (OrderAdopt orderAdopt : orderAdopts) {

            //设置为已取消
            orderAdopt.setState(2);

            //修改
            orderAdoptService.saveOrUpdate(orderAdopt);
        }


    }

    private String beforeMiddleHourTime(){

        Calendar nowAfter = Calendar.getInstance();
        //往前推30分钟  MINUTE：分钟
        nowAfter.add(Calendar.MINUTE, -30);
        //格式化条件
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //格式化结果
        return sdf.format(nowAfter.getTimeInMillis());
    }


    public static void main(String[] args) {
       /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        long time = 30*60*1000;//30分钟

        Date afterDate = new Date(now .getTime() + time);//30分钟后的时间

        Date beforeDate = new Date(now .getTime() - time);//30分钟前的时间

        System.out.println(sdf.format(afterDate ));

        System.out.println(sdf.format(beforeDate));*/




        Calendar nowAfter = Calendar.getInstance();
        nowAfter.add(Calendar.MINUTE, -30);
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String weNeedTime = sdf.format(nowAfter.getTimeInMillis());





        System.out.println(  sdf.format(nowAfter.getTimeInMillis()) );

    }
}